package com.qf.utils;

import java.sql.SQLException;

/**
 * @Description: 公用常量
 * @Data: 2022/8/31 18:41
 * @Pacakge: com.qf.utils
 * @ClassName: TransactionManager
 * @Author: fan
 * 和事务管理相关的工具类,它包含了开启事务,提交事务,回滚事务,释放资源
 */
public class TransactionManager {
    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }
    //开启事务
    public void beginTransaction(){
        try {
            //绑定当前线程的连接,并且关闭自动提交事务
            connectionUtils.getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //提交事务
    public void commitTransaction(){
        try {
            connectionUtils.getConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //事务回滚
    public void rollbackTransaction(){
        try {
            connectionUtils.getConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //释放资源
    public void release(){
        try {
            //将数据库连接对象归还到服务器的线程池中,但是此时的数据库连接对象与数据库还未解绑
            connectionUtils.getConnection().close();
            //解绑
            connectionUtils.removeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
